<script lang="ts" setup >
import { Map, View, Feature } from 'ol'
import { Circle } from 'ol/geom';
import Style from 'ol/style/Style';
import { computed, onMounted, ref, nextTick, reactive } from 'vue'
import { useMessage } from 'naive-ui'
import { useTianDiTu, useFullScreen, useDraw } from '@/hooks/map'
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import type { DrawEvent } from 'ol/interaction/Draw'
import { Overlay } from 'ol';





const { createTitleLayer } = useTianDiTu()
const key = 'b945c29c5388432e34b51b5d824d8157'

const map = ref<Map | null>(null)
const mapRef = ref(null)
onMounted(() => {
    // 创建一个覆盖来锚定弹出到地图上。
    const overlay = new Overlay({
        id: 'popup_1',
        element: document.getElementById("popup") as HTMLElement,
        autoPan: {
            animation: {
                duration: 250,
            },
        },
    });
    // 添加一个click处理程序来隐藏弹出窗口。
    nextTick(() => {
        const closer = document.getElementById("popup-closer") as HTMLElement
        if (closer) {
            closer.onclick = function () {
                overlay.setPosition(undefined);
                closer.blur();
                return false;
            }
        }
    })


    map.value = new Map({
        // 挂在容器
        target: "accessible_map",
        // 天地图底图
        layers: [
            createTitleLayer('vec_w', key),
            createTitleLayer('cia_w', key)
        ],
        controls: [], // 不包含任何控制组件
        overlays: [overlay],
        //视图
        view: new View({
            center: [113.75395, 34.76572],
            zoom: 8,
            projection: "EPSG:4326"
        })
    })
    // map.value?.on('singleclick', function (evt) {
    //     const coordinate = evt.coordinate;
    //     console.log('e', evt, coordinate);

    //     const hdms = toStringHDMS(toLonLat(coordinate));

    //     (document.getElementById('popup-content') as HTMLElement).innerHTML = '<p>You clicked here:</p><code>' + hdms + '</code>';
    //     overlay.setPosition(coordinate);
    // });
    window.$map = map.value
})
const message = useMessage()
const showZoom = () => {
    const zoom = map.value?.getView().getZoom()
    message.info(`当前地图缩放等级是:${zoom}`,
        {
            closable: true,
            duration: 2000
        })
}

const lessen = () => {
    const view = map.value?.getView()
    const zoom = (view?.getZoom() || 0) - 1
    if (zoom < 0) {
        message.warning("当前地图已是最小缩放等级，无法进行缩放", {
            closable: true,
            duration: 2000
        })
        return
    }
    view?.setZoom(zoom)
}
const magnify = () => {
    const view = map.value?.getView()
    const zoom = (view?.getZoom() || 0) + 1
    if (zoom >= 18.9) {
        message.warning("当前地图已是最大缩放等级，无法进行放大", {
            closable: true,
            duration: 2000
        })
        return
    }
    view?.setZoom(zoom)
}

const reset = () => {
    map.value?.getView()?.setZoom(8)
}

/** 全屏  ==========================  start  ==============*/
const { fullScreen, isFull } = useFullScreen('containder')
const fullText = computed(() => isFull.value ? "缩小" : "全屏")
/** 全屏  ==========================  end  ==============*/

/** 画圆  ==========================  start  ==============*/
const circleName = "custom_circle"
const circleFeature = new Feature({
    geometry: new Circle([113.75395, 34.76572], 0.2),
    properties: {
        name: "自定义圆"
    }
})
circleFeature.setStyle(
    new Style({
        renderer(coordinates, state) {
            const [[x, y], [x1, y1]] = coordinates;
            const ctx = state.context;
            const dx = x1 - x;
            const dy = y1 - y;
            const radius = Math.sqrt(dx * dx + dy * dy);

            const innerRadius = 0;
            const outerRadius = radius * 1.4;

            const gradient = ctx.createRadialGradient(
                x,
                y,
                innerRadius,
                x,
                y,
                outerRadius
            );
            gradient.addColorStop(0, 'rgba(255,0,0,0)');
            gradient.addColorStop(0.6, 'rgba(255,0,0,0.2)');
            gradient.addColorStop(1, 'rgba(255,0,0,0.8)');
            ctx.beginPath();
            ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
            ctx.fillStyle = gradient;
            ctx.fill();

            ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
            ctx.strokeStyle = 'rgba(255,0,0,1)';
            ctx.stroke();
        }
    })
)
const circleVectorLayer = new VectorLayer({
    source: new VectorSource(),
    properties: {
        name: circleName
    }
})
const circle = () => {
    // map.value?.addLayer(circleVectorLayer)
    // console.log('12312', map.value);
    const layer = map.value?.getAllLayers().find((layer) => layer.get("name") === circleName)
    !layer && map.value?.addLayer(circleVectorLayer)
    const source = circleVectorLayer.getSource()
    source?.clear()
    source?.addFeature(circleFeature)
    console.log('12312', circleVectorLayer.getSource()?.getFeatures());

}
/** 画圆  ==========================  end  ==============*/

const clear = () => {
    map.value?.getAllLayers().forEach((layer) => {
        if ('tian_di_tu_title_layer' !== layer.get("name")) map.value?.removeLayer(layer)
    })
}
const active = ref<boolean>(false)
const formData = reactive({
    mapx: '',
    mapy: ''
})
const submit = () => {
    console.log('34234', {...formData})
}
const { start, end } = useDraw({
    name: "point",
    type: 'Point',
    map: map.value as Map,
    drawend(evt: DrawEvent) {
        const point = evt.feature.getGeometry?.().getCoordinates?.()
        if (Array.isArray(point)) {
            formData.mapx = point[0]
            formData.mapy = point[1]
            active.value = true
        }
        console.log('evt.feature.getGeometry()', point);

        // map.value?.getOverlayById("popup_1").setPosition(evt.)

    }
})
const point = () => {
    start(map.value)
}



</script>
<template>
    <div id="containder">
        <div id="accessible_map" style="height: 100vh; width: 100%;" class="map-containder"></div>
        <div id="popup" class="ol-popup">
            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
            <div id="popup-content"></div>
        </div>
        <div class="btn-groups">
            <n-space btn-groups>
                <n-button type="primary" @click="showZoom">
                    显示地图缩放等级
                </n-button>
                <n-button type="primary" @click="lessen">
                    缩小
                </n-button>
                <n-button type="primary" @click="magnify">
                    放大
                </n-button>
                <n-button type="primary" @click="reset">
                    重置地图缩放等级
                </n-button>
                <n-button type="primary" @click="fullScreen">
                    {{ fullText }}
                </n-button>
                <n-button type="primary" @click="circle">
                    画圆
                </n-button>
                <n-button type="primary" @click="clear">
                    清空
                </n-button>

                <n-button type="primary" @click="point">
                    标点
                </n-button>
            </n-space>
        </div>

        <n-drawer v-model:show="active" :width="502" placement="left" :mask-closable="false">
            <n-drawer-content title="斯通纳" closable>
                <n-form ref="formRef" inline :label-width="80" :model="formData" size="large">
                    <n-form-item label="姓名" path="user.name">
                        <n-input v-model:value="formData.name" placeholder="输入姓名" />
                    </n-form-item>
                    <n-form-item>
                        <n-button attr-type="button" @click="submit">
                            提交
                        </n-button>
                    </n-form-item>
                </n-form>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>
<style scoped>
.map-containder {
    position: relative;
    height: calc(100vh - 110px);
    width: 100%;
}

.btn-groups {
    position: absolute;
    right: 100px;
    bottom: 200px;
    height: 20vh;
    padding: 5px;
    background-color: rgba(42, 207, 207, 0.336)
}

.ol-popup {
    position: absolute;
    background-color: white;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 280px;
}

.ol-popup:after,
.ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
}

.ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
}

.ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px;
}

.ol-popup-closer:after {
    content: "✖";
}
</style>